package org.aeon.server.handler.Inbound;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.User;
import org.aeon.entity.dto.UserVerificationDto;
import org.aeon.message.Message;
import org.aeon.message.request.LoginRequestMessage;
import org.aeon.message.response.LoginResponseMessage;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserServiceFactory;

import java.util.List;

/**
 * @author: MissingAeon
 * @date: 2024/1/25 11:59
 * @description: 登录请求消息处理程序
 */
@Slf4j
@ChannelHandler.Sharable
public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        final LoginResponseMessage resMsg = new LoginResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final UserVerificationDto userV = msg.getUserVerification();
        // 账号检查
        final User user = UserServiceFactory.getService().login(userV.getUsername(), userV.getPassword());
        if (user != null) {
            if (SessionFactory.getSession().getChannel(user.getId()) == null) {
                // 绑定
                SessionFactory.getSession().bind(ctx.channel(), user.getId());
                resMsg.setResponse(true, "登陆成功,上次登陆：" + user.getFinallyOnline());
                final String token = UserServiceFactory.getService().registerToken(user.getId(), userV.getUsername(), userV.getPassword());
                if (token == null) {
                    resMsg.setResponse(false, "服务繁忙");
                    ctx.writeAndFlush(resMsg);
                    SessionFactory.getSession().unbind(ctx.channel());
                    return;
                }
                resMsg.setToken(token);
                resMsg.setUser(user);

            } else {
                resMsg.setResponse(false, "重复登陆，请先退出再尝试");
            }
        } else {
            resMsg.setResponse(false, "用户名或密码错误");
        }
        ctx.writeAndFlush(resMsg);

        if (resMsg.isSuccess()) {
            assert user != null;
            afterLoggingIn(ctx, user.getId());
        }
    }

    private void afterLoggingIn(ChannelHandlerContext ctx, Long userId) {
        final List<Message> messages = UserServiceFactory.getService().getAllMessages(userId);
        messages.forEach(ctx::writeAndFlush);
    }

}
